package com.yizhuoyan.his.serviceimpl;

import com.yizhuoyan.his.ao.ChangePasswordAo;
import com.yizhuoyan.his.dao.SysAccountDao;
import com.yizhuoyan.his.dao.SysRoleDao;
import com.yizhuoyan.his.dto.SysAccountAuthorizationResult;
import com.yizhuoyan.his.dto.SysRoleSimpleDto;
import com.yizhuoyan.his.entity.SysAccountEntity;
import com.yizhuoyan.his.entity.SysRoleEntity;
import com.yizhuoyan.his.exception.HISException;
import com.yizhuoyan.his.service.SysAccountAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Objects;

@Transactional
@Valid
@Service
public class SysAccountAuthenticationServiceImpl implements SysAccountAuthenticationService {

    @Autowired
    SysAccountDao accountDao;
    @Autowired
    SysRoleDao roleDao;
    @Override
    public SysAccountAuthorizationResult login(@NotNull String account, @NotNull String password) throws Exception {

        //1参数验证（略）
        //2业务逻辑
        SysAccountEntity e = accountDao.selectOne("account", account);
        if(e==null){
            throw  new HISException("LoginFail","帐号和密码不匹配");
        }

        if(!Objects.equals(e.getPassword(),password)){
            throw  new HISException("LoginFail","帐号和密码不匹配");
        }
        //2.2 查找所属角色
        Long roleId = e.getRoleId();
        SysRoleEntity role = roleDao.selectById(roleId);
        //3组装业务结果
        SysAccountAuthorizationResult result = new SysAccountAuthorizationResult();
        result.setId(e.getId());
        result.setAccount(e.getAccount());
        result.setName(e.getNickname());
        result.setCreateTime(e.getCreateTime());
        result.setLastLoginTime(e.getLastLoginTime());
        result.setMainRole(SysRoleSimpleDto.of(role));
        return result;
    }

    @Override
    public void logout(String accountId) throws Exception {

    }

    @Override
    public void changePassword(ChangePasswordAo ao) throws Exception {

    }
}
